//
//  GGTitleView.swift
//  DongBaoDemo
//
//  Created by 陈志勇 on 2018/8/4.
//  Copyright © 2018年 陈志勇. All rights reserved.
//

import UIKit

class GGTitleView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    private var btns: [UIButton] = []
    private var titles: [String] = []
    private var previousBtn = UIButton()
    private var callBack: ((_ index: Int) -> ())?
    lazy private var underLine: UIView = {
        let underLine = UIView()
        underLine.backgroundColor = .red
        addSubview(underLine)
        return underLine
    }()
    private var selectIndex = 0 {
        didSet {
            moveUnderLine()
        }
    }
    
    
    init(frame: CGRect, titles: [String], titleColor: UIColor = .white) {
        super.init(frame: frame)
        
        self.titles = titles
        setupTitle(titles: titles, titleColor: titleColor)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if btns.count == 0 {
            return
        }
        
        let btnW = GGScreenW / CGFloat(btns.count)
        let btnH = GGToolBarHeight
        var btnX = CGFloat(0.0)
        let btnY = CGFloat(0.0)
        for i in 0..<btns.count {
            let btn = btns[i]
            btnX = btnW * CGFloat(i)
            btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
            addSubview(btn)
        }
        moveUnderLine()
        
    }
    
    
    private func setupTitle(titles: [String], titleColor: UIColor) {
        
        for title in titles {
            let btn = UIButton(type: .custom)
            btn.tag = btns.count + 666
            btn.setTitle(title, for: .normal)
            btn.setTitleColor(titleColor, for: .normal)
            btn.setTitleColor(.red, for: .selected)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
            btn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
            if btns.count == selectIndex {
                btn.isSelected = true
                previousBtn = btn
            }
            btns.append(btn)
        }
        // 强制重新布局
        setNeedsLayout()
    }
    
    private func moveUnderLine() {
        let selectedBtn = btns[selectIndex]
        guard let font = selectedBtn.titleLabel?.font else {
            return
        }
        let underLineWidth = getStrWidth(str: titles[selectIndex], font: font)
        UIView.animate(withDuration: 0.2) {
            self.underLine.center = CGPoint(x: selectedBtn.center.x, y: self.bounds.height - 1)
            self.underLine.bounds = CGRect(x: 0, y: 0, width: underLineWidth, height: 2)
        }
    }
    
    private func getStrWidth(str: String, font: UIFont) -> CGFloat {
        let attrs = [NSAttributedStringKey(rawValue: "NSFontAttributeName"): font]
        return (str as NSString).boundingRect(with: CGSize.zero, options: .usesLineFragmentOrigin, attributes: attrs, context: nil).size.width
    }
}

// MARK: - 对外回调
extension GGTitleView {
    func didSelectTitle(callBack: ((_ index: Int) -> ())?) {
        self.callBack = callBack
    }
    
}

// MARK: - 按钮点击
extension GGTitleView {
    @objc private  func btnAction(btn: UIButton) {
        
        let index = btn.tag - 666
        if index == selectIndex {
            return
        }
        btn.isSelected = !btn.isSelected
        previousBtn.isSelected = false
        
        // 发出通知
        guard let callback = callBack else {
            fatalError()
        }
        callback(index)
        
        selectIndex = index
        previousBtn = btn
    }
}
